<template>
<div>
    <van-pull-refresh v-model="refreshing" @refresh="handleRefresh()">
        <!--内容列表-->
        <van-list v-model:loading="loading"
            :finished="finished"
            offset="300"
            loading-text="正在努力加载中..."
            :finished-text="title&&postList.length < 1 ? '' : emptyText"
            @load="GetPostList()"
        >
            <div class="content-grid">
                <div v-for="item in postList" :key="item.id" class="post-card" @click="GoToDetail(item.id)">
                    <div class="post-image" :style="getPostImageStyle(item)">
                        <div v-if="shouldShowPostText(item)" :style="getPostTextStyle(item)">
                            {{ item.title }}
                        </div>
                    </div>
                    <div class="post-content">
                        <div class="post-title">{{ item.title }}</div>
                        <div class="post-footer">
                            <div class="post-author">
                                <div class="author-avatar" :style="{ backgroundImage: item.userAvatarUrl ? `url(${item.userAvatarUrl})` : '' }"></div>
                                <div class="author-name">{{ item.username ?? "账号已注销" }}</div>
                            </div>
                            <div class="post-stats">
                                <span>❤️ {{ formatNumber(item.likesCount) }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </van-list>

        <!--没有内容时的骨架屏-->
        <el-skeleton v-if="postList.length==0 && !finished" class="content-grid" animated :count="6" :throttle="250">
            <template #template>
                <div class="post-card">
                    <el-skeleton-item variant="image" style="width: 100%; height: 200px"/>
                    <div style="padding: 14px">
                        <el-skeleton-item variant="p" style="width: 50%" />
                        <div style="display: flex; align-items: center; justify-items: space-between;">
                            <el-skeleton-item variant="text" style="margin-right: 16px" />
                            <el-skeleton-item variant="text" style="width: 30%" />
                        </div>
                    </div>
                </div>
            </template>
        </el-skeleton>
    </van-pull-refresh>
</div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import api from '@/api/'
import { UserInfoStore } from '@/stores/userInfoStore'
import { TipStore } from '@/stores/tipStore'
import { formatNumber } from '@/utils/format.js'
import { getPostImageStyle, getPostTextStyle, shouldShowPostText } from '@/utils/imageBackground.js'

const route = useRoute()
const router = useRouter()

const user_Store = UserInfoStore()
const tip_Store = TipStore()

// 登录状态
const isLogin = computed(() => {
    return user_Store.userInfo?.id
})

// 组件通信
const props = defineProps({
    // 渲染的帖子列表类型
    tab: {
        type: String,
    },
    // 没有数据时的提示语
    emptyText: {
        type: String,
        default: '没有更多数据'
    }
})
const title = defineModel('title') // 获取父组件传递的参数--标题
const emit = defineEmits(['getResultNumber']); // 定义事件--向父容器传递数据总数


// 帖子列表
const postList = ref([])


// #region 辅助方法
// 错误处理
function isError(code){
    if(code != 1){
        tip_Store.errorTip("获取数据失败")
        loading.value = false; // 加载状态结束
        return true
    }
    return false
}

// 跳转详情页
function GoToDetail(opusId){
    router.push({
        path: '/OpusDetail',
        query: { id: opusId },
    });
}


// #endregion


// #region 请求数据
// 请求普通数据
const GetNormalData = async()=>{
    let uid = user_Store.userInfo.id
    // 如果未登录
    if(!isLogin){
        uid = null
    }
    // const res = await api.Post_GetAllByPage(currentPage.value, pageSize.value)
    const res = await api.Post_FeedHome(uid, currentPage.value, pageSize.value)
    if(isError(res.data.code)){ return null; }
    return res
}

// 根据我的关注请求数据
const GetDataByMyFollow = async()=>{
    const res = await api.Post_GetByPageAndMyFollow(user_Store.userInfo.id, currentPage.value, pageSize.value)
    if(isError(res.data.code)){ return null; }
    return res
}

// 根据帖子标题获取数据
const GetDataByTitle = async(title)=>{
    const res = await api.Post_GetByTitle(title, currentPage.value, pageSize.value)
    if(isError(res.data.code)){ return null; }
    return res
}
// #endregion


// #region 加载更多相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const loading = ref(false) // 上滑加载标识
const finished = ref(false) // 是否加载完成标识
const refreshing = ref(false); // 下拉刷新标识


// 获取数据
const GetPostList = async ()=>{

    // 如果正在下拉刷新
    if (refreshing.value) {
        postList.value = []; // 清空数据列表
        refreshing.value = false;
    }

    // 获取数据列表
    let res = null
    try{
        if(props.tab){
            if(props.tab == '关注'){
                res = await GetDataByMyFollow()
            }else{
                res = await GetNormalData()
            } 
        }else{
            if(title.value){
                res = await GetDataByTitle(title.value)
            }else{
                res = await GetNormalData()
            }
        }
        postList.value = [...postList.value, ...res.data.data.list]; // 将返回的列表中的每个元素添加到contentList中
        total.value = res.data.data.total;
        currentPage.value ++; // 页码加1
        if (res.data.data.list.length < pageSize.value) {
            finished.value = true; // 数据已经全部加载完成
        }
        emit('getResultNumber', total.value); // 向父组件传递数据总数信息
    }catch(error){
        console.log('发生错误：',error);
        finished.value = true; // 防止继续加载
    }finally{
        loading.value = false; // 加载状态结束
    }
}

// 重新加载数据
const reloadData = () =>{
    currentPage.value = 1;
    loading.value = true; // 显示加载中
    GetPostList();
}

// 下拉刷新
const handleRefresh = () => {
    finished.value = false;
    reloadData() // 重新加载数据
}

// 暴露给外部调用的加载数据方法（初始化数据）
const initData = () => {
    // 如果已经加载过数据，则不再重复加载
    if (postList.value.length > 0) {
        return;
    }
    reloadData() // 重新加载数据
}
// #endregion




// 暴露方法给父组件调用
defineExpose({
    initData
});

onMounted(async() => {
    console.log('PostList组件已挂载');
    // 只有"推荐"标签在挂载时自动加载数据
    if (props.tab === '推荐') {
       reloadData()
    }
    // "关注"标签的数据将在用户点击切换标签时通过initData方法加载
});
</script>


<style scoped lang="scss">
.content-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 10px;
    margin-top: 20px;
}

.post-card {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0,0,0,0.08);
    transition: transform 0.3s;
    cursor: pointer;
}

.post-card:hover {
    transform: translateY(-5px);
}

.post-image {
    width: 100%;
    height: 200px;
    // background: linear-gradient(45deg, #ff9a9e, #fecfef);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 14px;
}

.post-content {
    padding: 15px;
}

.post-title {
    font-size: 14px;
    line-height: 1.4;
    margin-bottom: 8px;
    display: -webkit-box;
    line-clamp: 2; /* 限制元素内文本显示的最大行数为 2 行。超出部分会被隐藏，并以省略号（...）表示 */
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.post-author {
    display: flex;
    align-items: center;
    gap: 8px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 12px;
}

.author-avatar {
    width: 24px;
    height: 24px;
    min-width: 24px;
    min-height: 24px;
    border-radius: 50%;
    background: #ff6b6b;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

.author-name {
    font-size: 12px;
    color: #666;
    overflow: hidden;
    text-overflow: ellipsis; /* 添加省略号 */
    white-space: nowrap; /* 确保文本在一行内 */
}

.post-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.post-stats {
    display: flex;
    gap: 15px;
    font-size: 12px;
    color: #999;
    white-space: nowrap; /* 确保文本在一行内 */
}

@media (max-width: 768px) {
  .content-grid {
    grid-template-columns: repeat(2, 1fr); /* 两列等宽 */
  }
}
</style>
